<template>
  <div id="app">
    <!-- 顶部操作栏 -->
    <div class="actions-bar">
      <div class="left">
        <el-checkbox v-model="selectAll" @change="handleSelectAll">全选</el-checkbox>
        <span class="selected-count" v-if="selectedCount > 0">已选择 {{ selectedCount }} 件商品</span>
      </div>
      <div class="right">
        <el-button type="danger" :disabled="!hasSelected" @click="batchDelete">
          <i class="el-icon-delete"></i> 批量删除
        </el-button>
        <el-button type="primary" :disabled="!hasSelected" @click="batchCheckout">
          <i class="el-icon-shopping-cart-full"></i> 去结算
        </el-button>
      </div>
    </div>

    <!-- 购物车列表 -->
    <div class="container">
      <div v-if="cartItems && cartItems.length > 0">
        <div v-for="(item, index) in cartItems" :key="item.itemId" class="cart-item">
          <div class="checkbox-container">
            <el-checkbox v-model="item.selected"></el-checkbox>
          </div>

          <img :src="item.image" alt="Product Image" class="product-image" @error="handleImageError">
          <div class="item-details">
            <h3 class="product-name">{{ item.name }}</h3>
            <p class="product-desc">{{ item.description }}</p>
            <div class="price-quantity">
              <p class="product-price">￥{{ item.price.toFixed(2) }}</p>
              <div class="quantity-controls">
                <el-button type="primary" size="mini" icon="el-icon-minus" @click="decrementQuantity(index)" :disabled="item.quantity <= 1"></el-button>
                <el-input-number v-model="item.quantity" :min="1" :max="99" size="mini" controls-position="right" @change="updateQuantity(index, $event)"></el-input-number>
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="incrementQuantity(index)"></el-button>
              </div>
            </div>
            <p class="item-total">小计：￥{{ (item.price * item.quantity).toFixed(2) }}</p>
          </div>

          <div class="item-actions">
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeItem(index)">删除</el-button>
            <el-button type="primary" size="mini" icon="el-icon-shopping-cart-2" @click="checkoutSingle(item)">结算</el-button>
          </div>
        </div>
      </div>

      <!-- 空购物车提示 -->
      <div v-if="!cartItems || cartItems.length === 0" class="empty-cart">
        <i class="el-icon-shopping-cart-2"></i>
        <p>购物车是空的，快去选购心仪的商品吧~</p>
        <el-button type="primary" @click="$router.push('/')">去购物</el-button>
      </div>
    </div>

    <!-- 底部结算栏 -->
    <div class="checkout-bar" v-if="cartItems.length > 0">
      <div class="checkout-info">
        <span>已选择 {{ selectedCount }} 件商品</span>
        <span class="total-price">合计：￥{{ totalPrice.toFixed(2) }}</span>
      </div>
      <el-button type="primary" size="medium" :disabled="!hasSelected" @click="batchCheckout">
        去结算 ({{ selectedCount }})
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: null,
      isAuthenticated: false,
      cartItems: [],
      selectAll: false,
      defaultImage: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png' // 使用在线默认图片
    };
  },
  computed: {
    selectedCount() {
      return this.cartItems.filter(item => item.selected).length;
    },
    hasSelected() {
      return this.selectedCount > 0;
    },
    totalPrice() {
      return this.cartItems
        .filter(item => item.selected)
        .reduce((total, item) => total + item.price * item.quantity, 0);
    }
  },
  created() {
    console.log('组件创建，开始加载购物车数据');
    this.loadUsercar();
  },
  mounted() {
    console.log('组件挂载完成，当前购物车数据:', this.cartItems);
  },
  updated() {
    console.log('组件更新，当前购物车数据:', this.cartItems);
  },
  watch: {
    '$route.params.id': {
      handler(newVal) {
        if (newVal) {
          console.log('Route parameter ID changed:', newVal);
          this.loadUsercar();
        } else {
          console.log('No valid route parameter ID found.');
        }
      },
      immediate: true
    },
    cartItems: {
      handler(newVal) {
        console.log('购物车数据变化:', newVal);
        this.selectAll = newVal.length > 0 && newVal.every(item => item.selected);
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    loadUsercar() {
      console.log('开始加载购物车数据');
      this.load();
    },
    load() {
      this.$message.info('正在加载购物车...');
      
      this.request.get("/cartitems/getCartList")
        .then(res => {
          console.log('购物车原始响应数据:', res);
          
          try {
            if (res.code === 1 && res.data && Array.isArray(res.data)) {
              this.cartItems = res.data.map(item => {
                console.log('处理购物车项:', item);
                return {
                  itemId: item.itemId,
                  name: item.name,
                  price: Number(item.price),
                  quantity: Number(item.quantity),
                  image: item.image,
                  description: `${item.name}的商品描述`,
                  selected: false,
                  totalPrice: Number(item.totalPrice)
                };
              });
              
              console.log('映射后的购物车数据:', this.cartItems);
              
              if (this.cartItems.length > 0) {
                this.$message.success(`成功加载 ${this.cartItems.length} 件商品`);
              } else {
                this.$message.info('购物车是空的');
              }
            } else {
              console.warn('响应数据格式不正确:', res);
              this.cartItems = [];
              this.$message.warning(res.msg || '购物车为空');
            }
          } catch (error) {
            console.error('处理购物车数据时出错:', error);
            this.$message.error('处理购物车数据时出错');
            this.cartItems = [];
          }
        })
        .catch(err => {
          console.error('加载购物车失败:', err);
          this.$message.error('加载购物车失败，请稍后重试');
          this.cartItems = [];
        });
    },
    handleSelectAll(val) {
      this.cartItems.forEach(item => item.selected = val);
    },
    incrementQuantity(index) {
      if (this.cartItems[index].quantity < 99) {
        this.cartItems[index].quantity++;
        this.updateCartItem(this.cartItems[index]);
      }
    },
    decrementQuantity(index) {
      if (this.cartItems[index].quantity > 1) {
        this.cartItems[index].quantity--;
        this.updateCartItem(this.cartItems[index]);
      }
    },
    updateQuantity(index, value) {
      this.cartItems[index].quantity = value;
      this.updateCartItem(this.cartItems[index]);
    },
    updateCartItem(item) {
      const updateData = {
        itemId: item.itemId,
        quantity: item.quantity
      };
      
      this.request.post('/cartitems/update', updateData).then(res => {
        if (res.code === '200') {
          this.$message.success('更新成功');
        } else {
          this.$message.error(res.msg || '更新失败');
        }
      }).catch(err => {
        console.error('更新购物车失败:', err);
        this.$message.error('更新失败，请重试');
      });
    },
    removeItem(index) {
      this.$confirm('确定要删除这件商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const item = this.cartItems[index];
        this.request.post('/cartitems/delete', { itemId: item.itemId })
          .then(res => {
            if (res.code === '200') {
              this.cartItems.splice(index, 1);
              this.$message.success('删除成功');
            } else {
              this.$message.error(res.msg || '删除失败');
            }
          })
          .catch(() => {
            this.$message.error('删除失败，请重试');
          });
      }).catch(() => {});
    },
    batchDelete() {
      const selectedItems = this.cartItems.filter(item => item.selected);
      if (selectedItems.length === 0) {
        this.$message.warning('请选择要删除的商品');
        return;
      }

      this.$confirm(`确定要删除选中的 ${selectedItems.length} 件商品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const itemIds = selectedItems.map(item => item.itemId);
        this.request.post('/cartitems/batchdelete', { itemIds })
          .then(res => {
            if (res.code === '200') {
              this.cartItems = this.cartItems.filter(item => !item.selected);
              this.$message.success('批量删除成功');
            } else {
              this.$message.error(res.msg || '批量删除失败');
            }
          })
          .catch(() => {
            this.$message.error('批量删除失败，请重试');
          });
      }).catch(() => {});
    },
    batchCheckout() {
      const selectedItems = this.cartItems.filter(item => item.selected);
      if (selectedItems.length === 0) {
        this.$message.warning('请选择要结算的商品');
        return;
      }
      
      // 存储选中的商品信息到 localStorage
      const checkoutInfo = {
        items: selectedItems,
        totalAmount: this.totalPrice,
        itemCount: selectedItems.length
      };
      localStorage.setItem('checkoutInfo', JSON.stringify(checkoutInfo));
      // 跳转到结算页面
      this.$router.push('/balance');
    },
    checkoutSingle(item) {
      const checkoutInfo = {
        items: [item],
        totalAmount: item.price * item.quantity,
        itemCount: 1
      };
      localStorage.setItem('checkoutInfo', JSON.stringify(checkoutInfo));
      this.$router.push('/balance');
    },
    handleImageError(e) {
      e.target.src = this.defaultImage;
    }
  }
};
</script>

<style scoped>
.app {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.actions-bar {
  background-color: white;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.selected-count {
  color: #606266;
  font-size: 14px;
}

.right {
  display: flex;
  gap: 10px;
}

.container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  padding: 20px;
}

.cart-item {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  position: relative;
  align-items: center;
}

.cart-item:last-child {
  border-bottom: none;
}

.checkbox-container {
  margin-right: 20px;
}

.product-image {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 8px;
  margin-right: 20px;
  transition: transform 0.3s;
}

.product-image:hover {
  transform: scale(1.05);
}

.item-details {
  flex: 1;
  min-width: 0;
}

.product-name {
  font-size: 16px;
  color: #303133;
  margin: 0 0 10px 0;
}

.product-desc {
  color: #909399;
  font-size: 14px;
  margin: 5px 0;
}

.price-quantity {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0;
}

.product-price {
  color: #ff4d4f;
  font-size: 18px;
  font-weight: bold;
  margin: 0;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.item-total {
  color: #ff4d4f;
  font-size: 14px;
  text-align: right;
  margin: 10px 0 0 0;
}

.item-actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-left: 20px;
}

.empty-cart {
  text-align: center;
  padding: 40px 0;
  color: #909399;
}

.empty-cart i {
  font-size: 48px;
  margin-bottom: 20px;
}

.checkout-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  padding: 15px 20px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  box-shadow: 0 -2px 12px 0 rgba(0,0,0,0.1);
  z-index: 100;
}

.checkout-info {
  margin-right: 20px;
}

.total-price {
  color: #ff4d4f;
  font-size: 20px;
  font-weight: bold;
  margin-left: 15px;
}

@media (max-width: 768px) {
  .cart-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .product-image {
    width: 100%;
    height: 200px;
    margin-right: 0;
    margin-bottom: 15px;
  }

  .item-actions {
    flex-direction: row;
    margin-left: 0;
    margin-top: 15px;
  }

  .checkout-bar {
    flex-direction: column;
    gap: 10px;
  }
}
</style>